<template>
	
	<view class="friend_Page">
		<headerinfo></headerinfo>
		<u-navbar title="聊天" :placeholder="true" leftIcon=" " :bgColor="bgColor" :titleStyle="titleStyle"></u-navbar>
		<view class="">
			<view class="chatAiBg" :style="[{background:useColorAsBg?`url(${background}) no-repeat center top;`:background}]"></view>
			<view class="tips color_fff size_12 align_c" :class="{ show: ajax.loading }" @tap="getHistoryMsg">
				{{ ajax.loadText }}
			</view>
		
			<view class="box-1" id="list-box">
				<view class="talk-list">
					<view v-for="(item, index) in talkList" :key="index" :id="`msg-${item.docId}`">
						<view class="item flex_col" :class="item.type == 1 ? 'push' : 'pull'">
							<image v-if="item.type == 1" :src="avatar" mode="aspectFill" class="pic"></image>
							<image v-else src="../../static/images/robbot.png" mode="aspectFill" class="pic"></image>
							<view class="content" v-if="item.type == 1">{{ item.content }}</view>
		
							<view class="content" v-else style="padding: 0px;">
								<zero-markdown-view :markdown="item.content"></zero-markdown-view>
								<view class="copyText" @click="copy(item.content)">复制</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="box-2">
				<view class="flex_col">
					<view class="setting" @click="toSetting()">
						<i class="iconfont">&#xe604;</i>
					</view>
					<view class="flex_grow">
						<textarea class="textareas" maxlength="256" v-model="content" placeholder="请输入聊天内容"
							placeholder-style="color:#adb1b9;"></textarea>
		
						<!-- 	<input type="text" maxlength="256" class="content" v-model="content" placeholder="请输入聊天内容"
							placeholder-style="color:#DDD;" :cursor-spacing="6" /> -->
					</view>
					<button class="send" @tap="send">发送</button>
				</view>
			</view>
		</view>
	</view>
	
</template>

<script>
	import {
		fetchEventSource
	} from "@microsoft/fetch-event-source";
	import * as TextEncoding from 'text-encoding-shim';
	import {
		apiBaseURL
	} from '../../common/config.js'
	export default {
		data() {

			return {
				bgColor: '#de4849',
				titleStyle: {
					color: '#fff'
				},
				talkList: [],
				ajax: {
					pageSize: 20, //每页数量
					lastDocId: '', //页码
					flag: true, // 请求开关
					loading: true, // 加载中
					loadText: '正在获取消息'
				},
				//我们的字段
				content: '',
				nowIndex: -1,
				requestTask: null,
				background: 'https://www.25175.net/images/mybg.jpg',
				useColorAsBg: true,
				avatar: '' //我的头像
			};
		},
		onShow() {
			this.getData()
		},
		mounted() {
			this.$nextTick(() => {
				this.getHistoryMsg();
				this.getAvatar();



			});
			setTimeout(() => {
				uni.pageScrollTo({
					scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
					duration: 0
				});
			}, 500)
		},
		onPageScroll(e) {
			if (e.scrollTop < 5) {
				this.getHistoryMsg();
			}

		},
		methods: {
			getData() {
				this.$api.getChatConfig().then(res => {
					console.log(res)
					if (res.background) {
						this.background = res.background
						this.useColorAsBg = res.useColorAsBg
					}

					// if(res.docId){
					// 	this.firstForm.docId = res.docId

					// 	this.firstForm.background = res.background
					// }
				})
			},
			//获取自己的头像
			getAvatar() {
				this.$api.myInfo().then(res => {
					console.log(res)
					this.avatar = res.avatar;
				})
			},
			// 获取历史消息
			getHistoryMsg() {


				if (!this.ajax.flag) {
					return;
				}
				// 此处用到 ES7 的 async/await 知识，为使代码更加优美。不懂的请自行学习。
				let get = async () => {
					this.hideLoadTips();
					this.ajax.flag = false;
					let data = await this.joinHistoryMsg();


					// 获取待滚动元素选择器，解决插入数据后，滚动条定位时使用
					let selector = '';

					if (this.ajax.lastDocId) {
						// 非第一页，则取历史消息数据的第一条信息元素
						if (this.talkList.length > 0) {
							selector = `#msg-${this.talkList[0].docId}`;
						}
					} else {
						if (data.length > 0) {
							// 第一页，则取当前消息数据的最后一条信息元素
							selector = `#msg-${data[data.length - 1].docId}`;
						}
					}

					// 将获取到的消息数据合并到消息数组中
					this.talkList = [...data, ...this.talkList];

					if (this.talkList.length == 0) {
						this.talkList.push({
							content: '我是您的AI管家，有什么问题尽管向我提问吧',
							type: 2
						})
						// this.nowIndex = this.talkList.length + 2
					}

					this.$nextTick(() => {
						// 设置当前滚动的位置
						this.setPageScrollTo(selector);
						this.hideLoadTips(true);

						if (this.ajax.lastDocId) {
							setTimeout(() => {
								this.ajax.flag = true;
							}, 200);
						} else {}
					});
				};
				get();
			},
			// 历史记录接口
			joinHistoryMsg() {
				// 此处用到 ES6 的 Promise 知识，不懂的请自行学习。
				return new Promise((done, fail) => {
					// 无数据请求接口，由 setTimeout 模拟，正式项目替换为 ajax 即可。
					let arr = [];

					this.$api.queryMyChatConvert(this.ajax).then(res => {
						let arrData = []
						if (res.list.length > 0) {
							res.list.reverse();
							res.list.forEach(item => {
								item.forEach(item2 => {
									arrData.push(item2)
								})
							})
						}
						this.ajax.lastDocId = res.lastDocId
						arr = arrData;
						console.log(arr)
						// arr.reverse();
						done(arr);

					})

				});
			},
			//阅读
			read() {
				let data = {
					buddyId: this.buddyId,
					currentDateTime: this.currentDateTime
				};
				this.$Request
					.post({
						url: '/mp/auth/postLetter/read',
						data
					})
					.then(res => {
						console.log(res);
					});
			},
			// 设置页面滚动位置
			setPageScrollTo(selector) {
				let view = uni
					.createSelectorQuery()
					.in(this)
					.select(selector);
				view.boundingClientRect(res => {
					uni.pageScrollTo({
						scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度，示意上面还有信息。
						duration: 0
					});
				}).exec();
			},
			// 隐藏加载提示
			hideLoadTips(flag) {
				if (flag) {
					this.ajax.loadText = '消息获取成功';
					setTimeout(() => {
						this.ajax.loading = false;
					}, 300);
				} else {
					this.ajax.loading = true;
					this.ajax.loadText = '正在获取消息';
				}
			},
			spliteDecode(value) {
				var target = value.match(/\\u\d+/g);
				if (target && target.length > 0) {
					target = target[0];
					var temp = value.replace(target, '{{@}}');
					target = target.replace('\\u', '');
					target = String.fromCharCode(parseInt(target));
					return temp.replace("{{@}}", target);
				} else {
					// value = value.replace( '\\u', '' );
					// return String.fromCharCode( parseInt( value, '10' ) )
					return value;
				}
			},
			getMessage(question) {
				const self = this


				let query = {
					base: {
						requestId: Math.floor(Math.random() * 1000000000) + '',
						clientId: 'minghui',
						debugMore: false
					},
					content: question,
				}
				
				this.$api2.sendMessag(query).then(res=>{
					let contentData = msg.data
					let index = self.talkList.length - 1
					
					self.talkList[index].content += contentData ? contentData : ''
					uni.pageScrollTo({
						scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
						duration: 0
					});
				})
			

			},
			copy(msg) {
				uni.setClipboardData({
					data: msg, // e是你要保存的内容
					success: function() {
						uni.showToast({
							title: '复制成功',
							icon: 'none'
						})
					}
				})
			},
			// 发送信息
			send() {
				if (!this.content) {
					uni.showToast({
						title: '请输入有效的内容',
						icon: 'none'
					});
					return;
				}


				let dataInfo = {
					content: this.content,
					type: 1,
					avatar: this.avatar
				};

				this.talkList.push(dataInfo);


				this.nowIndex = this.nowIndex + 2

				let dataInfo2 = {
					content: '',
					type: 2,
					avatar: this.avatar
				};

				this.talkList.push(dataInfo2);

				this.getMessage(this.content)
				this.$nextTick(() => {
					// 清空内容框中的内容
					this.content = '';
					uni.pageScrollTo({
						scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
						duration: 0
					});
				});


			},
			toSetting() {
				uni.navigateTo({
					url: '/pages/chat/setting'
				})
			}
		}
	};
</script>

<style lang="scss">
	@import './global.scss';

	.chatAiBg {
		background-size: cover!important;
		background-repeat: no-repeat;
		background-attachment: fixed;
		height: 100vh;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		top: 100rpx;
		z-index: -100;
	}

	.setting {
		.iconfont {
			font-size: 52rpx;
			color: #de4849;
			margin-right: 10rpx;
		}
	}

	page {
		background-color: #f3f3f3;
		font-size: 28rpx;
	}

	.copyText {
		padding: 0 20rpx;
		color: #8f8f8f;
	}

	/* 加载数据提示 */
	.tips {
		position: fixed;
		left: 0;
		top: var(--window-top);
		width: 100%;
		z-index: 9;
		background-color: rgba(0, 0, 0, 0.15);
		height: 72rpx;
		line-height: 72rpx;
		transform: translateY(-80rpx);
		transition: transform 0.3s ease-in-out 0s;

		&.show {
			transform: translateY(0);
		}
	}

	.box-1 {
		width: 100%;
		height: auto;
		padding-bottom: 100rpx;
		box-sizing: content-box;

		/* 兼容iPhoneX */
		margin-bottom: 0;
		margin-bottom: constant(safe-area-inset-bottom);
		margin-bottom: env(safe-area-inset-bottom);
	}

	.box-2 {
		position: fixed;
		left: 0;
		width: 100%;

		bottom: 0;
		/* #ifdef H5 */
		bottom: 98rpx;
		/* #endif */
		height: auto;
		z-index: 2;
		border-top: #e5e5e5 solid 1px;
		box-sizing: content-box;
		background-color: #f3f3f3;

		/* 兼容iPhoneX */
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		>view {
			padding: 0 20rpx;
			height: 140rpx;
		}

		.textareas {
			background-color: #fff;
			height: 124rpx;
			padding: 10rpx 20rpx;
			border-radius: 10rpx;
			font-size: 28rpx;
			width: 500rpx;
			box-sizing: border-box;
		}

		.content {
			background-color: #fff;
			height: 124rpx;
			padding: 0 20rpx;
			border-radius: 10rpx;
			font-size: 28rpx;
		}

		.send {
			background-color: #de4849;
			color: #fff;
			height: 64rpx;
			margin-left: 20rpx;
			border-radius: 32rpx;
			padding: 0;
			width: 120rpx;
			line-height: 62rpx;

			&:active {
				background-color: #5fc496;
			}
		}
	}

	.talk-list {
		padding-bottom: 80rpx;

		/* 消息项，基础类 */
		.item {
			padding: 20rpx 20rpx 0 20rpx;
			align-items: flex-start;
			align-content: flex-start;
			color: #333;

			.pic {
				width: 70rpx;
				height: 70rpx;
				border-radius: 50%;
			}

			.content {
				padding:10rpx 15rpx;
				border-radius: 4px;
				max-width: 590rpx;
				word-break: break-all;
				line-height: 52rpx;
				position: relative;
			}

			/* 收到的消息 */
			&.pull {
				.content {
					margin-left: 20rpx;
					background-color: #f5f6f8;
					border: 1px solid #e7e8ea;
					// &::after {
					// 	content: '';
					// 	display: block;
					// 	width: 0;
					// 	height: 0;
					// 	border-top: 16rpx solid transparent;
					// 	border-bottom: 16rpx solid transparent;
					// 	border-right: 20rpx solid #fff;
					// 	position: absolute;
					// 	top: 16rpx;
					// 	left: -18rpx;
					// }
				}
			}

			/* 发出的消息 */
			&.push {
				/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
				flex-direction: row-reverse;

				.content {
					margin-right: 20rpx;
					background-color: #e6f7ff;
					border: 1px solid #223850;

					// &::after {
					// 	content: '';
					// 	display: block;
					// 	width: 0;
					// 	height: 0;
					// 	border-top: 16rpx solid transparent;
					// 	border-bottom: 16rpx solid transparent;
					// 	border-left: 20rpx solid #a0e959;
					// 	position: absolute;
					// 	top: 16rpx;
					// 	right: -18rpx;
					// }
				}
			}
		}
	}
</style>